var app = angular.module('dashboardApp', ['ngRoute']);


app.controller('SearchForm', ["$scope", "$http", "placeService", function ($scope, $http, placeService) {
    $scope.location = ""
    console.log("Search controller is invoked")
/*

    $scope.getLocation = function () {
        console.log("Invoke getLocation: " + placeService.location())
        $scope.location = placeService.location();
    }
*/

    $scope.$watch(placeService.location, function (currentLocation, newLocation) {

        console.log("Location watcher start new location: (" + newLocation + ")")
        $scope.location = newLocation
        console.log("Getting guides id: ", newLocation)

        $http({
            method: "GET",
            url: "/gb/v01/guide/search",
            params: { place_id: $scope.location.place_id }
        }).success(function (data, status, headers, config) {
            console.log("guides data: ", data)

            if (angular.isDefined(data)) {
                $scope.guides = data
            } else {
                $scope.guides = data.error
            }
        })
        console.log("Location watcher finish")
    })
}]);


/*app.service('guideService', function ($rootScope, $q, $http) {
    console.log("Guide Service init start")

    this.getGuides = function (placeId) {
        console.log("Request guides placeId: " + placeId)

        var deferred = $q.defer();

        var request = $http({
            method: "GET",
            url: "/gb/v01/guide/search",
            params: { place_id: placeId}
        }).success(function (data, status, headers, config) {
            console.log("guides data: " + data)
            deferred.resolve(data);


        })
        return deferred.promise;
    }
})*/


app.service('placeService', function ($rootScope) {
    console.log("Place Service init start")
    var place = ""
    var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], { types: ['geocode'], types: ['(cities)'] });
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        $rootScope.$apply(function () {
            place = autocomplete.getPlace();
        });
    });
    this.location = function () {
        console.log("get location: (" + place + ")")
        return  place;
    };
})


app.controller('ExampleController2', ["$scope", "myUserService", function ($scope, myUserService) {
    console.log("Controller init")

    $scope.submit = function () {
        console.log("Login submit visited " + $scope.formData.username)
        myUserService.login($scope.formData)

        console.log("user = " + $scope.user)

    }
    $scope.$watch(myUserService.loggedIn, function (newvalue, oldvalue) {
        console.log("watched : old value - " + oldvalue + " . New value - " + newvalue)
        $scope.user = myUserService.getUser();
        $scope.user.isUser = newvalue;
    });
    $scope.logout = function () {
        myUserService.logout()

    }
}]);


app.service('myUserService', [ "$http", "transformRequestAsFormPost", function ($http, transformRequestAsFormPost) {

    var user = {};
    var loggedIn = false

    this.loggedIn = function () {
        console.log("Return logged in " + loggedIn);
        return loggedIn;
    }

    this.getUser = function () {
        console.log("Get user " + user)
        return user;
    }

    this.logout = function () {
        $http.get("/gb/v01/user/logout").success(function (data, status, headers, config) {
            console.log("Logout data: " + data)
        })
        loggedIn = false

    }
    this.login = function (formData) {

        console.log("Login start");

        var request = $http({
            method: "post",
            url: "/gb/v01/user/signin",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            transformRequest: transformRequestAsFormPost,

            data: formData

        }).success(function (data, status, headers, config) {

            console.log("Response got " + data.name + " ROLE: " + data.authorities[0].authority);

            user = data;
            console.log(user)
            loggedIn = true;
        }).
            error(function (data, status, headers, config) {
                user = data;
            });

    }
}]);


app.factory(
    "transformRequestAsFormPost",
    function () {
        function transformRequest(data) {
            return( serializeData(data) );
        }

        return( transformRequest );

        function serializeData(data) {

            if (!angular.isObject(data)) {
                return( ( data == null ) ? "" : data.toString() );
            }
            var buffer = [];
            for (var name in data) {
                if (!data.hasOwnProperty(name)) {
                    continue;
                }
                var value = data[ name ];
                buffer.push(
                        encodeURIComponent(name) +
                        "=" +
                        encodeURIComponent(( value == null ) ? "" : value)
                );
            }
            var source = buffer.join("&").replace(/%20/g, "+");
            return( source );
        }
    }
);
app.value(
    "$sanitize",
    function (html) {
        return( html );
    }
);



